package feizhou.untils.tools;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description :
 * @Autor : xiongjinpeng jpx_011@163.com
 * @Date : 2017年6月30日 下午5:27:00
 * @version :
 */
public class MsgUtil {

	private static Logger log = Logger.getLogger(MsgUtil.class);

	private static int connectTimeout = 30000; // 默认连接超时30秒

	private static int readTimeout = 30000; // 默认读取超时20秒
	
	private static String areaCodes = DispatcherUtil.getInstance().getProperty("area_code");
	
	/**签名。 国际短信时需要，国内短信会自动带有签名*/
	public static String sign = DispatcherUtil.getInstance().getProperty("sign");
	
	/**
	 * 验证区号是否有效
	 * @return
	 */
    public static boolean validateAreaCode(String areaCode) {
        if (StringUtil.isEmpty(areaCode) && StringUtil.isEmpty(areaCodes)) {
			String[] areaCodeArr = areaCodes.split(",");
            for (String code : areaCodeArr) {
                if (code.equals(areaCode)) {
                    return true;
                }
            }
        }
        return false;
    }
    
	public static String sendPost(String urlString, Map<String, Object> parameters, Map<String, String> propertys) throws Exception {
		HttpPost httpRequest = null;
		String response=null;
        org.apache.http.client.HttpClient client = null;
		try {
			/* 建立HTTPost对象 */
			httpRequest = new HttpPost(urlString);
			if (propertys != null) {
				for (String key : propertys.keySet()) {
					httpRequest.setHeader(key, propertys.get(key));
				}
			}
			/*
			 * NameValuePair实现请求参数的封装
			 */
			if (parameters != null) {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (String key : parameters.keySet()) {
					if(parameters.get(key)!=null){
						params.add(new BasicNameValuePair(key, parameters.get(key).toString()));
					}
				}
				/* 添加请求参数到请求对象 */
				httpRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			}

			client = new DefaultHttpClient();
			/* 设置超时时间 */
			client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
			client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
			/* 发送请求并等待响应 */
		 HttpResponse httpResponse = client.execute(httpRequest);
			/* 若状态码为200 ok */
			int status = httpResponse.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				/* 读返回数据 */
				response = EntityUtils.toString(httpResponse.getEntity());
				return response;
			} else {
				response = EntityUtils.toString(httpResponse.getEntity());
				log.error("sendPost error,status：" + status + ",msg:" + response + ",url:" + urlString);
			}
		} catch (Exception e) {
			log.error("sendPost error", e);
		} finally {
            if (httpRequest != null) {
                httpRequest.releaseConnection();
            }
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
        }
		return null;
	}
	/**
	 * 批量发送短信
	 * @Autor : xiongjinpeng  jpx_011@163.com
	 * @Date  : 2017年7月3日 上午10:27:09 
	 * @param uri
	 * @param account
	 * @param pswd
	 * @param mobiles 多个手机用逗号隔开
	 * @param content
	 * @param needstatus
	 * @param product
	 * @param extno
	 * @return
	 * @throws Exception
	 */
	public static String batchSend(String uri, String account, String pswd, String mobiles, String content, boolean needstatus, String product, String extno) throws Exception {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("account", account);
		parameters.put("pswd", pswd);
		parameters.put("mobile", mobiles);
		parameters.put("needstatus", needstatus);
		parameters.put("msg", content);
		parameters.put("product", product);
		parameters.put("extno", extno);
		String res = sendPost(uri + "HttpBatchSendSM", parameters, null);
		return res;
	}

	public static void main(String[] args) {
//		uri=http://222.73.117.158/msg/
//
//			Sn_zs=Sdjwkj888_hwzs
//			Pwd_zs=Hwzs88888
//		boolean needstatus = true;//是否需要状态报告，需要true，不需要false
//        String product = null;//产品ID
//        String extno = null;//扩展码
//		try {
//			batchSend("http://222.73.117.158/msg/", "Sdjwkj888_hwzs", "Hwzs88888", "15914173180", "测试", true, null, null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	    
//	    InternationalSmsReq req = new InternationalSmsReq();
	    
//	    req.setMobile("8618664361731");
//	    req.setMsg("测试1");
//	    
//	    String res = HttpUtils.sendJson(req.getUri(), null, null, req);
//	    System.out.println(res);
	    

	    
	}
}
